package com.example.demo1.Controller;

import com.example.demo1.dao.BookRepository;
import com.example.demo1.pojo.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import java.util.List;
import java.util.Optional;

@Controller
public class BookController {

    @Autowired
    private BookRepository bookRepository;

    // 显示所有书籍
    @GetMapping("/books")
    public String listBooks(Model model) {
        List<Book> books = bookRepository.findAll();
        model.addAttribute("books", books);
        return "books";
    }

    // 显示添加书籍表单1
    @GetMapping("/books/new")
    public String showNewBookForm(Model model) {
        model.addAttribute("book", new Book());
        return "new_book";
    }

    // 保存新书籍
    @PostMapping("/books/save")
    public String saveBook(@ModelAttribute("book") Book book) {
        bookRepository.save(book);
        return "redirect:/books";
    }

    // 显示编辑书籍表单
    @GetMapping("/books/{id}/edit")
    public String showEditBookForm(@PathVariable("id") int id, Model model) {
        Book book = bookRepository.findById(id).orElseThrow(() -> new RuntimeException("没找到该图书"));
        model.addAttribute("book", book);
        return "edit_book";
    }

    // 更新书籍
    @PostMapping("/books/{id}/update")
    public String updateBook(@PathVariable("id") int id, @ModelAttribute("book") Book bookDetails) {
        Book book = bookRepository.findById(id).orElseThrow(() -> new RuntimeException("没找到该图书"));
        book.setName(bookDetails.getName());
        book.setAuthor(bookDetails.getAuthor());
        book.setPress(bookDetails.getPress());
        book.setStatus(bookDetails.getStatus());
        bookRepository.save(book);
        return "redirect:/books";
    }

    // 删除书籍
    @GetMapping("/books/{id}/delete")
    public String deleteBook(@PathVariable("id") int id) {
        Book book = bookRepository.findById(id).orElseThrow(() -> new RuntimeException("没找到该图书"));
        bookRepository.delete(book);
        return "redirect:/books";
    }

    //根据id查询图书详细信息
    @GetMapping("/books/search")
    public String searchBookById(@RequestParam("id") int id, Model model) {
        Optional<Book> bookOptional = bookRepository.findById(id);
        if (bookOptional.isPresent()) {
            model.addAttribute("book", bookOptional.get());
            return "book_details"; // 假设我们有一个名为book_details的页面来显示详细信息
        } else {
            model.addAttribute("errorMessage", "未找到ID为 " + id + " 的图书。");
            return "books"; // 如果没有找到，我们可以重定向回图书列表页面并显示错误消息
        }
    }
}